package com.tomatozq.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
import java.io.IOException;

public class PDFBuilder extends PdfPageEventHelper {
    private String srcFilePath;
    private String markImagePath;
    private String destFilePath;
    public BaseFont bf;
    public PdfTemplate tpl;

    public PDFBuilder(String srcFilePath,String markImagePath,String destFilePath){
        this.srcFilePath = srcFilePath;
        this.markImagePath = markImagePath;
        this.destFilePath = destFilePath;
    }

    @Override
    public void onOpenDocument(PdfWriter pdfWriter, Document document) {
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            tpl = pdfWriter.getDirectContent().createTemplate(100, 100);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        super.onOpenDocument(pdfWriter, document);
    }

    @Override
    public void onEndPage(PdfWriter pdfWriter, Document document) {
//        super.onEndPage(pdfWriter, document);
//      this.addPage(pdfWriter, document);
        try {
            addPage(pdfWriter, document);
            addWatermark(pdfWriter);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public void onCloseDocument(PdfWriter pdfWriter, Document document) {
        tpl.beginText();
        tpl.setFontAndSize(bf, 12);
        tpl.setTextMatrix(0, 0);
        tpl.showText("共" + (pdfWriter.getPageNumber() - 1) + "页");
        tpl.endText();
    }

    private void addPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();

        String text = "第" + writer.getPageNumber() + "页 / ";
        float textSize = bf.getWidthPoint(text, 12);
        float textBase = document.bottom();
        cb.beginText();
        cb.setFontAndSize(bf, 12);
        // for odd pagenumbers, show t

        Rectangle pageRect = writer.getPageSize();

        float left = (pageRect.getWidth() - textSize)/2;

        cb.setTextMatrix(left, textBase);

        cb.showText(text);
        cb.endText();
        cb.addTemplate(tpl, left + textSize, textBase);
        cb.restoreState();
    }

    private void addWatermark(PdfWriter pdfWriter) throws Exception{
        PdfContentByte content = pdfWriter.getDirectContentUnder();
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.1f);// 透明度设置

        content.beginText();

        Image img = Image.getInstance(markImagePath);// 插入图片水印
//        img.setRotation(-20);// 旋转 弧度
//        img.setRotationDegrees(45);// 旋转 角度
        // img.scaleAbsolute(200,100);//自定义大小
        // img.scalePercent(50);//依照比例缩放

        //最底部
//      img.setAbsolutePosition(0, 0);
        int imgHeight = (int)img.getHeight();
        int imgWidth = (int)img.getWidth();

        Rectangle pageRect = pdfWriter.getPageSize();

        for (int y = 0; y < pageRect.getHeight();y += imgHeight) {
            for (int x = 0; x < pageRect.getWidth(); x+= imgWidth) {
                content.setGState(gs1);// 图片水印 透明度

                img.setAbsolutePosition(x,y);
                content.addImage(img);// 图片水印
            }
        }

        content.endText();
    }

    public void create(){
        try {
            PdfReader reader = new PdfReader(this.srcFilePath);

            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(this.destFilePath));
            writer.setPageEvent(this);

            document.open();

            PdfContentByte content = writer.getDirectContent();

            int pageNum = reader.getNumberOfPages();

            //将原pdf文件通过writer进行处理
            for(int i=1;i<=pageNum;i++){
                document.newPage();
                PdfImportedPage page = writer.getImportedPage(reader, i);
                content.addTemplate(page,0,0);
            }

            document.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        PDFBuilder builder = new PDFBuilder("G:/watermark/PowerDesigner教程(完整)1.pdf",
                "G:/watermark/watermark.png",
                "G:/watermark/dest.pdf");

        builder.create();
    }
}
